package com.hcb.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author 11314
 * @description TODO
 * @date 2022/10/19 9:31
 */
@Component
public class aliyunoss {
    @Value("${aliyun.endpoint}")
    String endpoint;
    @Value("${aliyun.bucketName}")
    String bucketName;
    @Value("${aliyun.accessKeyId}")
    String accessKeyId;
    @Value("${aliyun.accessKeySecret}")
    String accessKeySecret;

    /**
     *
     * @param file
     * @return 文件地址
     */
    public String uploud(MultipartFile file){
        String filename=file.getOriginalFilename();
        if(!filename.substring(filename.indexOf('.')).equals(".pdf")){
            throw new RuntimeException("文件类型只能是pdf");
        }
        OSS ossclient=new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        try {
            InputStream inputStream=file.getInputStream();
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            filename = uuid+"="+filename;
            ossclient.putObject(bucketName,filename,inputStream);
            ossclient.shutdown();
            return "https://"+bucketName+"."+endpoint+"/"+filename;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("error");
        }
    }
    public String uploadimg(MultipartFile file){
        String filename=file.getOriginalFilename();
        OSS ossclient=new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        try {
            InputStream inputStream=file.getInputStream();
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            filename = uuid+"="+filename;
            ossclient.putObject(bucketName,filename,inputStream);
            ossclient.shutdown();
            return "https://"+bucketName+"."+endpoint+"/"+filename;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("error");
        }
    }
}
